package cn.schoolwow.ams.module.block.listBlock.daoBlock.databaseTable.initial.flow;

import cn.schoolwow.ams.domain.block.list.common.AMSFieldOption;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instanceList.QueryInstanceList;

import java.util.List;

public class SetDatabaseTableListBlockFieldsFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        Entity entity = (Entity) flowContext.checkData("entity");
        String[] fieldNames = (String[]) flowContext.getData("fieldNames");

        List<Property> propertyList = QueryInstanceList.newQuery(entity.properties)
                .addInQuery("column", fieldNames)
                .execute()
                .getList();
        if(null==fieldNames||fieldNames.length==0){
            for(Property property:propertyList){
                addAMSFieldOption(property, flowContext);
            }
        }else{
            for(String fieldName:fieldNames){
                for(Property property:propertyList){
                    if(property.column.equalsIgnoreCase(fieldName)){
                        addAMSFieldOption(property, flowContext);
                        break;
                    }
                }
            }
        }
    }

    @Override
    public String name() {
        return "设置ClazzBlock字段列表通用流程";
    }

    private void addAMSFieldOption(Property property, FlowContext flowContext){
        List<AMSFieldOption> amsFieldOptionList = (List<AMSFieldOption>) flowContext.getData("amsFieldOptionList");

        AMSFieldOption amsFieldOption = new AMSFieldOption();
        amsFieldOption.name = property.name;
        amsFieldOption.label = property.comment;
        amsFieldOption.property = property;
        amsFieldOptionList.add(amsFieldOption);

        flowContext.startFlow(new InitialDatabaseTableListBlockFieldOptionFlow())
                .putCurrentCompositeFlowData("amsFieldOption", amsFieldOption)
                .execute();
    }
}
